<template>
    <div class="manage-container">
        <!-- card body -->
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :row-key="getRowKey"
            :fetch-api="fetchApi()">
            <template #headerOperate>
                <el-button v-auth="'QW_DATA'" type="primary" @click="syncData">
                    <el-icon class="sync_data"> <refresh /> </el-icon>同步企微数据
                </el-button>
            </template>
        </ZwTable>
        <!--明细-->
        <ZWDrawer ref="DrawerRef" @close="handleClose">
            <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-change="handleClick">
                <el-tab-pane label="客户" name="cust">
                    <DrawerTable
                        v-if="activeName == 'cust'"
                        ref="DrawerTableRef1"
                        :cust-data="custData"
                        :total="total"
                        :item-id="formData.id"
                        :active-name="activeName"
                        @searchData="getCustList"
                        @close="handleCloseDrawer"></DrawerTable>
                </el-tab-pane>
                <el-tab-pane label="客户群" name="custGroup">
                    <DrawerTable
                        v-if="activeName == 'custGroup'"
                        ref="DrawerTableRef2"
                        :group-data="groupData"
                        :item-id="formData.id"
                        :totalg="totalg"
                        :active-name="activeName"
                        @searchData="getGroupList"
                        @close="handleCloseDrawer"></DrawerTable>
                </el-tab-pane>
            </el-tabs>
        </ZWDrawer>
        <!-- 分配员工 -->
        <!-- <ZWDepart ref="DepartRef" @submit="getDeparts" /> -->
    </div>
</template>

<script lang="tsx" setup>
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';
import ZWDrawer from '@/components/ZWDrawer.vue';
import DrawerTable from './components/DrawerTable.vue';
import { getSetionId, IsNotEmpty, AFold, tableH, reSize } from '@/utils/utils';
import { reactive, ref, onMounted, computed, watch } from 'vue';
import { useStore } from '@/store';
import { ElLoading, ElMessage } from 'element-plus';
import { quitList, quitSync } from '@/api/employe/employeemanage/quit';
import { custDetail, custGroupDetail } from '@/api/employe/employeemanage/quit';
import { deepCopy } from '@/utils/helper';

const tabH = ref('500px');
const formData = reactive({
    id: '',
    keyword: '',
    assign_ids: [],
    status: -1,
    page: 1,
    page_size: 15
});
const custData = ref([]);
const groupData = ref([]);
//const drawerData = ref([])
// 当前页和全部页的切换
const options = [
    {
        value: '当前页',
        label: '当前页'
    }
];
const DrawerRef = ref(null);
const DrawerTableRef1 = ref(null);
const DrawerTableRef2 = ref(null);
const store = useStore();
const DepartRef = ref(null);
const activeName = ref('cust');
const creators = ref([]);

const formInline = reactive({
    work_user_search: '',
    status: 0,
    start_time: '',
    end_time: '',
    page_size: 15,
    page: 1
});
const getRowKey = (row: any) => {
    return row.id;
};
//获取明细
const getDetail = (val: any) => {
    DrawerRef.value.drawer = true;
    DrawerRef.value.width = 1000;
    DrawerRef.value.isShow = false;
    DrawerRef.value.title =
        val.zw_work_user_info.name +
        '-' +
        (IsNotEmpty(val.department_list) ? getSetionId('name', val.department_list).join('、') : '');
    formData.id = val.id;
};

//同步企微数据
const syncData = () => {
    const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });
    quitSync().then((res: any) => {
        loading.close();
        ElMessage.success('同步企微数据成功！');
    });
};
//------table表格
//切换客户or客户群
const handleClick = (tab: string, event: Event) => {
    if (activeName.value == 'cust') {
        getCustList(formData);
    } else {
        getGroupList(formData);
    }
};
//获取客户信息
const total = ref('');
const getCustList = (val: any) => {
    val.id = formData.id;
    custDetail(val).then((res: any) => {
        if (IsNotEmpty(res)) {
            custData.value = res.data;
            total.value = res.total;
            store.dispatch('pageTotal', res.total);
        } else {
            store.dispatch('pageTotal', 0);
        }
    });
};
//获取客户群信息
const totalg = ref('');
const getGroupList = (val: any) => {
    val.id = formData.id;
    custGroupDetail(val).then((res: any) => {
        if (IsNotEmpty(res)) {
            groupData.value = res.data;
            totalg.value = res.total;
            store.dispatch('pageTotal', res.total);
        } else {
            store.dispatch('pageTotal', 0);
        }
    });
};
const handleCloseDrawer = () => {
    DrawerRef.value.drawer = false;
};
const handleClose = () => {
    tableRef.value.reload();
};
const defaultParams = {
    work_user_search: '', //创建人id
    status: 0,
    time: [] //创建时间
};

const tableRef = ref<HTMLElement | null>(null);
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '员工信息',
            name: 'work_user_search',
            value: '',
            type: 'input',
            placeholder: '请输入员工姓名'
        },
        {
            label: '分配状态',
            name: 'status',
            value: [],
            type: 'select',
            placeholder: '请选择',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    setTimeout(() => {
                        resolve([
                            { id: 0, name: '全部' },
                            { id: 1, name: '分配完成' },
                            { id: 2, name: '未分配' }
                        ]);
                    }, 300);
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '离职日期',
            name: 'time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        }
    ];
});
const search = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...v,
        group_id: store.getters.group_id
    };
};
const reset = (v: any) => {
    tableRef.value.getTable().clearSelection();
    state.searchParams = {
        ...deepCopy(defaultParams),
        group_id: store.getters.group_id
    };
};

const onBtn = (row: any) => {
    return (
        <el-button class="edit-btn" size="small" v-auth="DETAIL_LEAVE" onClick={() => getDetail(row)}>
            明细
        </el-button>
    );
};

// 表格
const tableOption = [
    // {
    //   type: 'selection',
    //   width: 55,
    //   fixed: 'left',
    //   reserveSelection: true
    // },
    {
        prop: 'zw_work_user_info',
        label: '离职员工信息',
        minWidth: 260,
        render({ row, column, index }) {
            if (row.zw_work_user_info) {
                return (
                    <div>
                        {row.zw_work_user_info.name ? (
                            <el-avatar
                                shape="square"
                                size={50}
                                src={
                                    row.zw_work_user_info.avatar ||
                                    'https://img-scrm-dev.keyid.cn/keyid-scrm-server/avatar/cust_default.png'
                                }
                                class="avatar"></el-avatar>
                        ) : (
                            <img src="@/assets/image/account/default_avatar.png" alt={row.name} class="avatar" />
                        )}

                        <span>{row.zw_work_user_info.name}</span>
                        {row.zw_work_user_info.gender == 0 ? (
                            <img class="sex" src="/static/customer/sex_0.png" alt="" />
                        ) : row.zw_work_user_info.gender == 1 ? (
                            <img class="sex" src="/static/customer/sex_1.png" alt="" />
                        ) : row.zw_work_user_info.gender == 2 ? (
                            <img class="sex" src="/static/customer/sex_2.png" alt="" />
                        ) : (
                            <div></div>
                        )}
                    </div>
                );
            }
        }
    },
    {
        prop: 'department_list',
        label: '所在部门',
        minWidth: 280,
        render({ row, column, index }) {
            return IsNotEmpty(row.department_list) ? getSetionId('name', row.department_list).join('、') : '--';
        }
    },
    {
        prop: 'quit_time',
        label: '离职时间',
        width: 180
    },
    {
        prop: 'cust_left_nums',
        label: '待移交客户数',
        width: 120
    },
    {
        prop: 'groupchat_left_nums',
        label: '待移交客户群数',
        width: 120
    },
    {
        prop: 'cust_handovering_num',
        label: '移交中客户数',
        width: 120
    },
    {
        prop: 'groupchat_handovering_num',
        label: '移交中客户群数',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        width: 150,
        fixed: 'right',
        isOperate: true,
        renderOperate({ row }) {
            return onBtn(row);
        }
    }
];
const fetchApi = () => {
    // 获取文件列表
    // return getFissionList
    return quitList;
};
</script>

<style scoped lang="scss">
.switchPage {
    display: flex;
    align-items: center;
    justify-content: end;
    margin: 10px 0 20px 10px;

    .sync_data {
        margin-right: 5px;
    }

    .page {
        width: 110px;
        height: 36px;
    }

    :deep .el-select .el-input__inner {
        // background: #f9f9f9;
        border-radius: 1px;
        border: 1px solid #eaeaea;
    }
}

.mc-header {
    background-color: #f9f9f9;

    .el-date-editor {
        width: 100%;
    }

    .zw-search-form {
        padding: 16px;
        margin-bottom: 16px;
        background-color: #f9f9f9;

        .el-row {
            display: flex;
            flex-wrap: wrap;
            position: relative;
            box-sizing: border-box;
            margin: -8px -10px;

            .el-col {
                margin: 8px 0;

                &:last-of-type {
                    flex: auto;
                    text-align: right;
                }

                .el-form-item {
                    margin-bottom: 0;
                    width: 100%;

                    .el-form-item__label-wrap {
                        .el-form-item__label {
                            font-size: 14px;
                            font-family: STHeitiSC-Light, STHeitiSC;
                            font-weight: 300;
                            color: #33302d;
                        }
                    }

                    .el-form-item__content {
                        .el-input,
                        .el-select,
                        .el-date-editor {
                            width: 100%;
                        }
                    }
                }
            }
        }
    }
}

.manage-container {
    height: calc(100vh - 142px);
    padding: 24px;
    border: 1px solid #eaeaea;
    border-radius: 4px;
    box-sizing: border-box;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }

    .img {
        width: 80px;
    }

    .high_light {
        border: 1px solid #ff6b00;
        color: #ff6b00;
    }

    .empty {
        height: 400px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        .emty_img {
            transform: translateX(15%);
        }

        .emty_title {
            margin-top: -25px;
        }
    }
}

.high_light {
    border: 1px solid #ff6b00;
    color: #ff6b00;
}

:deep(.avatar) {
    margin-right: 10px;
    vertical-align: middle;
}

.isMale {
    width: 18px;
    line-height: 18px;
    border-radius: 50%;
    display: inline-block;
    color: #fff;
    background-color: #75ddf4;
    text-align: center;
    margin-left: 5px;
}

.isfeMale {
    background-color: #f474bf;
}

.demo-tabs {
    margin-top: 10px;
}

:deep(.sex) {
    vertical-align: middle;
    margin-left: 2px;
    width: 18px;
    height: 18px;
}
</style>
